package com.benshou.bsoa.service.dingding;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.benshou.bsoa.config.AttendanceProperties;
import com.benshou.bsoa.dto.dingding.Attend;
import com.benshou.bsoa.dto.dingding.Result;
import com.benshou.bsoa.utils.CreateAccessTokenUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiAttendanceGetcolumnvalRequest;
import com.dingtalk.api.response.OapiAttendanceGetcolumnvalResponse;
import com.taobao.api.internal.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.benshou.bsoa.constants.AttendanceConstant.*;
import static com.benshou.bsoa.enums.AttendanceFieldEnum.ACTUAL_ATTENDANCE;
import static com.benshou.bsoa.enums.AttendanceFieldEnum.SHOULD_ATTENDANCE;

/**
 * 考勤数据统计的业务逻辑层
 * @auth hyh
 * @date 2025/04/28
 */
@Service
@RequiredArgsConstructor
public class AttendService {
    @Autowired
    private CreateAccessTokenUtil createAccessTokenUtil;

    @Value("${dingding.benshou.attendance_id_list}")
    private String attendanceIdList; // 考勤ID列表

    @Autowired
    private AttendanceProperties attendanceProperties;

    @Value("${dingtalk.api.url}")
    private String apiUrl; // 可配置的DingTalk API URL

    /**
     * 获取考勤数据的统计
     * @param attend
     */
    public List<Result> getAttendanceData(Attend attend) throws Exception{
        DingTalkClient client = new DefaultDingTalkClient(apiUrl);
        OapiAttendanceGetcolumnvalRequest req = new OapiAttendanceGetcolumnvalRequest();
        req.setUserid(attend.getUserId());
        req.setColumnIdList(attendanceIdList);
        req.setFromDate(StringUtils.parseDateTime(attend.getFromDate()));
        req.setToDate(StringUtils.parseDateTime(attend.getToDate()));
        OapiAttendanceGetcolumnvalResponse rsp = client.execute(req, createAccessTokenUtil.getToken());
        return  analyseAttendanceData(rsp);
    }



    /**
     * 获取考勤数据的统计
     * @Param res
     * 应出勤天数
     * 实际出勤天数
     */
    public List<Result> analyseAttendanceData(OapiAttendanceGetcolumnvalResponse rsp) {
        List<Result> resultList = new ArrayList<>();

        // 定义统计变量
        int shouldAttendanceDays = 0;
        int attendanceDays = 0;

        // 解析返回结果
        JSONObject jsonObject = JSONObject.parseObject(rsp.getBody());
        JSONObject resultObj = jsonObject.getJSONObject(RESULT);
        JSONArray columnValsArray = resultObj.getJSONArray(COLUMN_VALS);
        // 遍历考勤数据
        for (int i = 0; i < columnValsArray.size(); i++) {
            JSONObject columnItem = columnValsArray.getJSONObject(i);
            JSONArray dailyVals = columnItem.getJSONArray(COLUMN_VALS);
            String id = columnItem.getJSONObject(COLUMN_VO).getString(ID);

            if (id == null) {
                continue;
            }
            // 判断考勤统计 应出勤天数
            if (id.equals(attendanceProperties.getShouldAttendanceDays())) {
                for (int j = 0; j < dailyVals.size(); j++) {
                    JSONObject dailyVal = dailyVals.getJSONObject(j);
                    String value = dailyVal.getString(VALUE);
                    // 如果值是 "1" 或 "1.0"，表示应出勤
                    if (ONE_FLOAT.equals(value) || ONE.equals(value)) {
                        shouldAttendanceDays++;
                    }
                }
                //实际出勤天数
            } else if (id.equals(attendanceProperties.getAttendanceDays())) {
                for (int j = 0; j < dailyVals.size(); j++) {
                    JSONObject dailyVal = dailyVals.getJSONObject(j);
                    String value = dailyVal.getString(VALUE);
                    // 如果值是 "1" 或 "1.0"，表示有出勤
                    if (ONE_FLOAT.equals(value) || ONE.equals(value)) {
                        attendanceDays++;
                    }
                }
            }
        }
        // 在循环结束后，添加结果到 resultList
        resultList.add(new Result(SHOULD_ATTENDANCE.getLabel(), shouldAttendanceDays));
        resultList.add(new Result(ACTUAL_ATTENDANCE.getLabel(), attendanceDays));
        return resultList;
    }
}
